public class BM4 {


    public static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public static ListNode Merge(ListNode pHead1, ListNode pHead2) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

        while (pHead1 != null && pHead2 != null) {
            if (pHead1.val < pHead2.val) {
                current.next = pHead1;
                pHead1 = pHead1.next;
            } else {
                current.next = pHead2;
                pHead2 = pHead2.next;
            }
            current = current.next;
        }

        // 将剩余部分直接连接到current后面
        current.next = (pHead1 != null) ? pHead1 : pHead2;

        return dummy.next;
    }

    public static void main(String[] args) {


        // 构建链表1: 1 -> 3 -> 5
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(3);
        l1.next.next = new ListNode(5);

        // 构建链表2: 2 -> 4 -> 6
        ListNode l2 = new ListNode(2);
        l2.next = new ListNode(4);
        l2.next.next = new ListNode(6);

        // 合并两个有序链表
        ListNode mergedList = Merge(l1, l2);

        // 输出合并后的链表
        while (mergedList != null) {
            System.out.print(mergedList.val + " ");
            mergedList = mergedList.next;
        }
    }

}
